home *** CD-ROM | disk | FTP | other *** search
/ Aminet 32 / Aminet 32 (1999)(Schatztruhe)[!][Aug 1999].iso / Aminet / dev / lang / Python151_Src.lha / Python1.5_Source / Modules / rotormodule.c < prev    next >
C/C++ Source or Header  |  1998-01-25  |  15KB  |  665 lines

  1. /***********************************************************
  2. Copyright 1994 by Lance Ellinghouse,
  3. Cathedral City, California Republic, United States of America.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its 
  8. documentation for any purpose and without fee is hereby granted, 
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in 
  11. supporting documentation, and that the name of Lance Ellinghouse
  12. not be used in advertising or publicity pertaining to distribution 
  13. of the software without specific, written prior permission.
  14.  
  15. LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO
  16. THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  17. FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE BE LIABLE FOR ANY SPECIAL, 
  18. INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING 
  19. FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, 
  20. NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION 
  21. WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  22.  
  23. ******************************************************************/
  24.  
  25. /* This creates an encryption and decryption engine I am calling
  26.    a rotor due to the original design was a harware rotor with
  27.    contacts used in Germany during WWII.
  28.  
  29. Rotor Module:
  30.  
  31. -  rotor.newrotor('key') -> rotorobject  (default of 6 rotors)
  32. -  rotor.newrotor('key', num_rotors) -> rotorobject
  33.  
  34. Rotor Objects:
  35.  
  36. -  ro.setkey('string') -> None (resets the key as defined in newrotor().
  37. -  ro.encrypt('string') -> encrypted string
  38. -  ro.decrypt('encrypted string') -> unencrypted string
  39.  
  40. -  ro.encryptmore('string') -> encrypted string
  41. -  ro.decryptmore('encrypted string') -> unencrypted string
  42.  
  43. NOTE: the {en,de}cryptmore() methods use the setup that was
  44.       established via the {en,de}crypt calls. They will NOT
  45.       re-initalize the rotors unless: 1) They have not been
  46.       initalized with {en,de}crypt since the last setkey() call;
  47.       2) {en,de}crypt has not been called for this rotor yet.
  48.  
  49. NOTE: you MUST use the SAME key in rotor.newrotor()
  50.       if you wish to decrypt an encrypted string.
  51.       Also, the encrypted string is NOT 0-127 ASCII. 
  52.       It is considered BINARY data.
  53.  
  54. */
  55.  
  56. /* Rotor objects */
  57.  
  58. #include "Python.h"
  59. #include "mymath.h"
  60.  
  61. #ifndef TRUE
  62. #define TRUE    1
  63. #endif
  64. #ifndef FALSE
  65. #define FALSE    0
  66. #endif
  67.  
  68. typedef struct {
  69.     PyObject_HEAD
  70.     int seed[3];
  71.         short key[5];
  72.     int  isinited;
  73.     int  size;
  74.     int  size_mask;
  75.         int  rotors;
  76.     unsigned char *e_rotor;             /* [num_rotors][size] */
  77.     unsigned char *d_rotor;             /* [num_rotors][size] */
  78.     unsigned char *positions;         /* [num_rotors] */
  79.     unsigned char *advances;         /* [num_rotors] */
  80. } Rotorobj;
  81.  
  82. #include "protos/rotormodule_protos.h"
  83.  
  84. staticforward PyTypeObject Rotor_Type;
  85.  
  86. #define is_rotor(v)        ((v)->ob_type == &Rotor_Type)
  87.  
  88.  
  89. /* This defines the necessary routines to manage rotor objects */
  90.  
  91. static void
  92. set_seed(r) 
  93.     Rotorobj *r;
  94. {
  95.     r->seed[0] = r->key[0];
  96.     r->seed[1] = r->key[1];
  97.     r->seed[2] = r->key[2];
  98.     r->isinited = FALSE;
  99. }
  100.     
  101. /* Return the next random number in the range [0.0 .. 1.0) */
  102. static double
  103. r_random(r)
  104.     Rotorobj *r;
  105. {
  106.     int x, y, z;
  107.     double val, term;
  108.  
  109.     x = r->seed[0];
  110.     y = r->seed[1];
  111.     z = r->seed[2];
  112.  
  113.     x = 171 * (x % 177) - 2 * (x/177);
  114.     y = 172 * (y % 176) - 35 * (y/176);
  115.     z = 170 * (z % 178) - 63 * (z/178);
  116.     
  117.     if (x < 0) x = x + 30269;
  118.     if (y < 0) y = y + 30307;
  119.     if (z < 0) z = z + 30323;
  120.     
  121.     r->seed[0] = x;
  122.     r->seed[1] = y;
  123.     r->seed[2] = z;
  124.  
  125.     term = (double)(
  126.         (((double)x)/(double)30269.0) + 
  127.         (((double)y)/(double)30307.0) + 
  128.         (((double)z)/(double)30323.0)
  129.         );
  130.     val = term - (double)floor((double)term);
  131.  
  132.     if (val >= 1.0)
  133.         val = 0.0;
  134.  
  135.     return val;
  136. }
  137.  
  138. static short
  139. r_rand(r, s)
  140.     Rotorobj *r;
  141.     short s;
  142. {
  143.     return (short)((short)(r_random(r) * (double)s) % s);
  144. }
  145.  
  146. static void
  147. set_key(r, key)
  148.     Rotorobj *r;
  149.     char *key;
  150. {
  151.     unsigned long k1=995, k2=576, k3=767, k4=671, k5=463;
  152.     int i;
  153.     int len = strlen(key);
  154.  
  155.     for (i = 0; i < len; i++) {
  156.         unsigned short ki = Py_CHARMASK(key[i]);
  157.  
  158.         k1 = (((k1<<3 | k1>>13) + ki) & 65535);
  159.         k2 = (((k2<<3 | k2>>13) ^ ki) & 65535);
  160.         k3 = (((k3<<3 | k3>>13) - ki) & 65535);
  161.         k4 = ((ki - (k4<<3 | k4>>13)) & 65535);
  162.         k5 = (((k5<<3 | k5>>13) ^ ~ki) & 65535);
  163.     }
  164.     r->key[0] = (short)k1;
  165.     r->key[1] = (short)(k2|1);
  166.     r->key[2] = (short)k3;
  167.     r->key[3] = (short)k4;
  168.     r->key[4] = (short)k5;
  169.  
  170.     set_seed(r);
  171. }
  172.  
  173.  
  174.  
  175. /* These define the interface to a rotor object */
  176. static Rotorobj *
  177. rotorobj_new(num_rotors, key)
  178.     int num_rotors;
  179.     char *key;
  180. {
  181.     Rotorobj *xp;
  182.  
  183.     xp = PyObject_NEW(Rotorobj, &Rotor_Type);
  184.     if (xp == NULL)
  185.         return NULL;
  186.     set_key(xp, key);
  187.  
  188.     xp->size = 256;
  189.     xp->size_mask = xp->size - 1;
  190.     xp->size_mask = 0;
  191.     xp->rotors = num_rotors;
  192.     xp->e_rotor = NULL;
  193.     xp->d_rotor = NULL;
  194.     xp->positions = NULL;
  195.     xp->advances = NULL;
  196.  
  197.     if (!(xp->e_rotor = PyMem_NEW(unsigned char, num_rotors * xp->size)))
  198.         goto finally;
  199.     if (!(xp->d_rotor = PyMem_NEW(unsigned char, num_rotors * xp->size)))
  200.         goto finally;
  201.     if (!(xp->positions = PyMem_NEW(unsigned char, num_rotors)))
  202.         goto finally;
  203.     if (!(xp->advances = PyMem_NEW(unsigned char, num_rotors)))
  204.         goto finally;
  205.  
  206.     return xp;
  207.  
  208.   finally:
  209.     PyMem_XDEL(xp->e_rotor);
  210.     PyMem_XDEL(xp->d_rotor);
  211.     PyMem_XDEL(xp->positions);
  212.     PyMem_XDEL(xp->advances);
  213.     Py_DECREF(xp);
  214.     return (Rotorobj*)PyErr_NoMemory();
  215. }
  216.  
  217.  
  218. /* These routines impliment the rotor itself */
  219.  
  220. /*  Here is a fairly sophisticated {en,de}cryption system.  It is based on
  221.     the idea of a "rotor" machine.  A bunch of rotors, each with a
  222.     different permutation of the alphabet, rotate around a different amount
  223.     after encrypting one character.  The current state of the rotors is
  224.     used to encrypt one character.
  225.  
  226.     The code is smart enought to tell if your alphabet has a number of
  227.     characters equal to a power of two.  If it does, it uses logical
  228.     operations, if not it uses div and mod (both require a division).
  229.  
  230.     You will need to make two changes to the code 1) convert to c, and
  231.     customize for an alphabet of 255 chars 2) add a filter at the begining,
  232.     and end, which subtracts one on the way in, and adds one on the way
  233.     out.
  234.  
  235.     You might wish to do some timing studies.  Another viable alternative
  236.     is to "byte stuff" the encrypted data of a normal (perhaps this one)
  237.     encryption routine.
  238.  
  239.     j'
  240.  
  241.  */
  242.  
  243. /* Note: the C code here is a fairly straightforward transliteration of a
  244.  * rotor implemented in lisp.  The original lisp code has been removed from
  245.  * this file to for simplification, but I've kept the docstrings as
  246.  * comments in front of the functions.
  247.  */
  248.  
  249.  
  250. /* Set ROTOR to the identity permutation */
  251. static void
  252. RTR_make_id_rotor(r, rtr)
  253.     Rotorobj *r;
  254.     unsigned char *rtr;
  255. {
  256.     register int j;
  257.     register int size = r->size;
  258.     for (j = 0; j < size; j++) {
  259.         rtr[j] = (unsigned char)j;
  260.     }
  261. }
  262.  
  263.  
  264. /* The current set of encryption rotors */
  265. static void
  266. RTR_e_rotors(r)
  267.     Rotorobj *r;
  268. {
  269.     int i;
  270.     for (i = 0; i < r->rotors; i++) {
  271.         RTR_make_id_rotor(r, &(r->e_rotor[(i*r->size)]));
  272.     }
  273. }
  274.  
  275. /* The current set of decryption rotors */
  276. static void
  277. RTR_d_rotors(r)
  278.     Rotorobj *r;
  279. {
  280.     register int i, j;
  281.     for (i = 0; i < r->rotors; i++) {
  282.         for (j = 0; j < r->size; j++) {
  283.             r->d_rotor[((i*r->size)+j)] = (unsigned char)j;
  284.         }
  285.     }
  286. }
  287.  
  288. /* The positions of the rotors at this time */
  289. static void
  290. RTR_positions(r)
  291.     Rotorobj *r;
  292. {
  293.     int i;
  294.     for (i = 0; i < r->rotors; i++) {
  295.         r->positions[i] = 1;
  296.     }
  297. }
  298.  
  299. /* The number of positions to advance the rotors at a time */
  300. static void
  301. RTR_advances(r) 
  302.     Rotorobj *r;
  303. {
  304.     int i;
  305.     for (i = 0; i < r->rotors; i++) {
  306.         r->advances[i] = 1;
  307.     }
  308. }
  309.  
  310. /* Permute the E rotor, and make the D rotor its inverse
  311.  * see Knuth for explanation of algorithm.
  312.  */
  313. static void
  314. RTR_permute_rotor(r, e, d)
  315.     Rotorobj *r;
  316.     unsigned char *e;
  317.     unsigned char *d;
  318. {
  319.     short i = r->size;
  320.     short q;
  321.     unsigned char j;
  322.     RTR_make_id_rotor(r,e);
  323.     while (2 <= i) {
  324.         q = r_rand(r,i);
  325.         i--;
  326.         j = e[q];
  327.         e[q] = (unsigned char)e[i];
  328.         e[i] = (unsigned char)j;
  329.         d[j] = (unsigned char)i;
  330.     }
  331.     e[0] = (unsigned char)e[0];
  332.     d[(e[0])] = (unsigned char)0;
  333. }
  334.  
  335. /* Given KEY (a list of 5 16 bit numbers), initialize the rotor machine.
  336.  * Set the advancement, position, and permutation of the rotors
  337.  */
  338. static void
  339. RTR_init(r)
  340.     Rotorobj *r;
  341. {
  342.     int i;
  343.     set_seed(r);
  344.     RTR_positions(r);
  345.     RTR_advances(r);
  346.     RTR_e_rotors(r);
  347.     RTR_d_rotors(r);
  348.     for (i = 0; i < r->rotors; i++) {
  349.         r->positions[i] = (unsigned char) r_rand(r,r->size);
  350.         r->advances[i] = (1+(2*(r_rand(r,r->size/2))));
  351.         RTR_permute_rotor(r,
  352.                   &(r->e_rotor[(i*r->size)]),
  353.                   &(r->d_rotor[(i*r->size)]));
  354.     }
  355.     r->isinited = TRUE;
  356. }
  357.  
  358. /* Change the RTR-positions vector, using the RTR-advances vector */
  359. static void
  360. RTR_advance(r)
  361.     Rotorobj *r;
  362. {
  363.     register int i=0, temp=0;
  364.     if (r->size_mask) {
  365.         while (i < r->rotors) {
  366.             temp = r->positions[i] + r->advances[i];
  367.             r->positions[i] = temp & r->size_mask;
  368.             if ((temp >= r->size) && (i < (r->rotors - 1))) {
  369.                 r->positions[(i+1)] = 1 + r->positions[(i+1)];
  370.             }
  371.             i++;
  372.         }
  373.     } else {
  374.         while (i < r->rotors) {
  375.             temp = r->positions[i] + r->advances[i];
  376.             r->positions[i] = temp%r->size;
  377.             if ((temp >= r->size) && (i < (r->rotors - 1))) {
  378.                 r->positions[(i+1)] = 1 + r->positions[(i+1)];
  379.             }
  380.             i++;
  381.         }
  382.     }
  383. }
  384.  
  385. /* Encrypt the character P with the current rotor machine */
  386. static unsigned char
  387. RTR_e_char(r, p)
  388.     Rotorobj *r;
  389.     unsigned char p;
  390. {
  391.     register int i=0;
  392.     register unsigned char tp=p;
  393.     if (r->size_mask) {
  394.         while (i < r->rotors) {
  395.             tp = r->e_rotor[(i*r->size) +
  396.                        (((r->positions[i] ^ tp) &
  397.                      r->size_mask))];
  398.             i++;
  399.         }
  400.     } else {
  401.         while (i < r->rotors) {
  402.             tp = r->e_rotor[(i*r->size) +
  403.                        (((r->positions[i] ^ tp) %
  404.                      (unsigned int) r->size))];
  405.             i++;
  406.         }
  407.     }
  408.     RTR_advance(r);
  409.     return ((unsigned char)tp);
  410. }
  411.  
  412. /* Decrypt the character C with the current rotor machine */
  413. static unsigned char
  414. RTR_d_char(r, c)
  415.     Rotorobj *r;
  416.     unsigned char c;
  417. {
  418.     register int i = r->rotors - 1;
  419.     register unsigned char tc = c;
  420.  
  421.     if (r->size_mask) {
  422.         while (0 <= i) {
  423.             tc = (r->positions[i] ^
  424.                   r->d_rotor[(i*r->size)+tc]) & r->size_mask;
  425.             i--;
  426.         }
  427.     } else {
  428.         while (0 <= i) {
  429.             tc = (r->positions[i] ^
  430.                   r->d_rotor[(i*r->size)+tc]) %
  431.                 (unsigned int) r->size;
  432.             i--;
  433.         }
  434.     }
  435.     RTR_advance(r);
  436.     return(tc);
  437. }
  438.  
  439. /* Perform a rotor encryption of the region from BEG to END by KEY */
  440. static void
  441. RTR_e_region(r, beg, len, doinit)
  442.     Rotorobj *r;
  443.     unsigned char *beg;
  444.     int len;
  445.     int doinit;
  446. {
  447.     register int i;
  448.     if (doinit || r->isinited == FALSE)
  449.         RTR_init(r);
  450.     for (i = 0; i < len; i++) {
  451.         beg[i] = RTR_e_char(r, beg[i]);
  452.     }
  453. }
  454.  
  455. /* Perform a rotor decryption of the region from BEG to END by KEY */
  456. static void
  457. RTR_d_region(r, beg, len, doinit)
  458.     Rotorobj *r;
  459.     unsigned char *beg;
  460.     int len;
  461.     int doinit;
  462. {
  463.     register int i;
  464.     if (doinit || r->isinited == FALSE)
  465.         RTR_init(r);
  466.     for (i = 0; i < len; i++) {
  467.         beg[i] = RTR_d_char(r, beg[i]);
  468.     }
  469. }
  470.  
  471.  
  472.  
  473. /* Rotor methods */
  474. static void
  475. rotor_dealloc(xp)
  476.     Rotorobj *xp;
  477. {
  478.     PyMem_XDEL(xp->e_rotor);
  479.     PyMem_XDEL(xp->d_rotor);
  480.     PyMem_XDEL(xp->positions);
  481.     PyMem_XDEL(xp->advances);
  482.     PyMem_DEL(xp);
  483. }
  484.  
  485. static PyObject * 
  486. rotorobj_encrypt(self, args)
  487.     Rotorobj *self;
  488.     PyObject * args;
  489. {
  490.     char *string = NULL;
  491.     int len = 0;
  492.     PyObject *rtn = NULL;
  493.     char *tmp;
  494.  
  495.     if (!PyArg_Parse(args, "s#", &string, &len))
  496.         return NULL;
  497.     if (!(tmp = PyMem_NEW(char, len+5))) {
  498.         PyErr_NoMemory();
  499.         return NULL;
  500.     }
  501.     memset(tmp, '\0', len+1);
  502.     memcpy(tmp, string, len);
  503.     RTR_e_region(self, (unsigned char *)tmp, len, TRUE);
  504.     rtn = PyString_FromStringAndSize(tmp, len);
  505.     PyMem_DEL(tmp);
  506.     return(rtn);
  507. }
  508.  
  509. static PyObject * 
  510. rotorobj_encrypt_more(self, args)
  511.     Rotorobj *self;
  512.     PyObject * args;
  513. {
  514.     char *string = NULL;
  515.     int len = 0;
  516.     PyObject *rtn = NULL;
  517.     char *tmp;
  518.  
  519.     if (!PyArg_Parse(args, "s#", &string, &len))
  520.         return NULL;
  521.     if (!(tmp = PyMem_NEW(char, len+5))) {
  522.         PyErr_NoMemory();
  523.         return NULL;
  524.     }
  525.     memset(tmp, '\0', len+1);
  526.     memcpy(tmp, string, len);
  527.     RTR_e_region(self, (unsigned char *)tmp, len, FALSE);
  528.     rtn = PyString_FromStringAndSize(tmp, len);
  529.     PyMem_DEL(tmp);
  530.     return(rtn);
  531. }
  532.  
  533. static PyObject * 
  534. rotorobj_decrypt(self, args)
  535.     Rotorobj *self;
  536.     PyObject * args;
  537. {
  538.     char *string = NULL;
  539.     int len = 0;
  540.     PyObject *rtn = NULL;
  541.     char *tmp;
  542.  
  543.     if (!PyArg_Parse(args, "s#", &string, &len))
  544.         return NULL;
  545.     if (!(tmp = PyMem_NEW(char, len+5))) {
  546.         PyErr_NoMemory();
  547.         return NULL;
  548.     }
  549.     memset(tmp, '\0', len+1);
  550.     memcpy(tmp, string, len);
  551.     RTR_d_region(self, (unsigned char *)tmp, len, TRUE);
  552.     rtn = PyString_FromStringAndSize(tmp, len);
  553.     PyMem_DEL(tmp);
  554.     return(rtn);
  555. }
  556.  
  557. static PyObject * 
  558. rotorobj_decrypt_more(self, args)
  559.     Rotorobj *self;
  560.     PyObject * args;
  561. {
  562.     char *string = NULL;
  563.     int len = 0;
  564.     PyObject *rtn = NULL;
  565.     char *tmp;
  566.  
  567.     if (!PyArg_Parse(args, "s#", &string, &len))
  568.         return NULL;
  569.     if (!(tmp = PyMem_NEW(char, len+5))) {
  570.         PyErr_NoMemory();
  571.         return NULL;
  572.     }
  573.     memset(tmp, '\0', len+1);
  574.     memcpy(tmp, string, len);
  575.     RTR_d_region(self, (unsigned char *)tmp, len, FALSE);
  576.     rtn = PyString_FromStringAndSize(tmp, len);
  577.     PyMem_DEL(tmp);
  578.     return(rtn);
  579. }
  580.  
  581. static PyObject * 
  582. rotorobj_setkey(self, args)
  583.     Rotorobj *self;
  584.     PyObject * args;
  585. {
  586.     char *key;
  587.  
  588.     if (!PyArg_ParseTuple(args, "s", &key))
  589.         return NULL;
  590.  
  591.     set_key(self, key);
  592.     Py_INCREF(Py_None);
  593.     return Py_None;
  594. }
  595.  
  596. static struct PyMethodDef
  597. rotorobj_methods[] = {
  598.     {"encrypt",    (PyCFunction)rotorobj_encrypt},
  599.     {"encryptmore",    (PyCFunction)rotorobj_encrypt_more},
  600.     {"decrypt",    (PyCFunction)rotorobj_decrypt},
  601.     {"decryptmore",    (PyCFunction)rotorobj_decrypt_more},
  602.     {"setkey",    (PyCFunction)rotorobj_setkey, 1},
  603.     {NULL,        NULL}        /* sentinel */
  604. };
  605.  
  606.  
  607. /* Return a rotor object's named attribute. */
  608. static PyObject * 
  609. rotorobj_getattr(s, name)
  610.     Rotorobj *s;
  611.     char *name;
  612. {
  613.     return Py_FindMethod(rotorobj_methods, (PyObject*)s, name);
  614. }
  615.  
  616.  
  617. statichere PyTypeObject Rotor_Type = {
  618.     PyObject_HEAD_INIT(&PyType_Type)
  619.     0,                /*ob_size*/
  620.     "rotor",            /*tp_name*/
  621.     sizeof(Rotorobj),        /*tp_size*/
  622.     0,                /*tp_itemsize*/
  623.     /* methods */
  624.     (destructor)rotor_dealloc,    /*tp_dealloc*/
  625.     0,                /*tp_print*/
  626.     (getattrfunc)rotorobj_getattr,    /*tp_getattr*/
  627.     0,                /*tp_setattr*/
  628.     0,                /*tp_compare*/
  629.     0,                /*tp_repr*/
  630.     0,                              /*tp_hash*/
  631. };
  632.  
  633.  
  634. static PyObject * 
  635. rotor_rotor(self, args)
  636.     PyObject * self;
  637.     PyObject * args;
  638. {
  639.     Rotorobj *r;
  640.     char *string;
  641.     int len;
  642.     int num_rotors = 6;
  643.  
  644.     if (!PyArg_ParseTuple(args, "s#|i", &string, &len, &num_rotors))
  645.         return NULL;
  646.  
  647.     r = rotorobj_new(num_rotors, string);
  648.     return (PyObject *)r;
  649. }
  650.  
  651.  
  652.  
  653. static struct PyMethodDef
  654. rotor_methods[] = {
  655.     {"newrotor",  rotor_rotor, 1},
  656.     {NULL,        NULL}             /* sentinel */
  657. };
  658.  
  659.  
  660. void
  661. initrotor()
  662. {
  663.     (void)Py_InitModule("rotor", rotor_methods);
  664. }
  665.